﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using UIT.Style;

namespace UIT.Converters
{
    public class ColorConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return (sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string s = value as string;
            if (s != null)
            {
                return FromString(s);
            }
            return base.ConvertFrom(context, culture, value);
        }

        public static string ToString(Color color)
        {
            return "#" + ((color.Value << 8) >> 8).ToString("x6");
        }

        internal static Color FromString(string s)
        {
            byte[] arvb = new byte[4];
            if (s.Length > 0 && s[0] == '#')
            {
                int index = 0;
                int lengthToParse, indexToParse = 1;
                switch (s.Length)
                {
                    case 4:
                        lengthToParse = 1;
                        index = 1;
                        break;
                    case 5:
                        lengthToParse = 1;
                        break;
                    case 7:
                        lengthToParse = 2;
                        index = 1;
                        break;
                    case 9:
                        lengthToParse = 2;
                        break;
                    default:
                        return default(Color);
                }
                if (index == 1)
                    arvb[arvb.Length - 1] = byte.MaxValue;
                for (index = arvb.Length - 1 - index; index >= 0; index--)
                {
                    string component = s.Substring(indexToParse, lengthToParse);
                    if (lengthToParse == 1)
                        component += component;
                    arvb[index] = (byte)int.Parse(component, System.Globalization.NumberStyles.AllowHexSpecifier);
                    indexToParse += lengthToParse;
                }
                return new Color(BitConverter.ToUInt32(arvb, 0));

            }
            System.Reflection.FieldInfo field = typeof(Colors).GetField(s, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
            if (field == null)
                return Colors.Empty;
            return (Color)field.GetValue(null);
        }
    }
}
